/**
 * @version 1.0
 * @author Ha Giang
 * @date
 */
package Communications;

import Configuration.Utils;
import java.io.*;
import java.net.*;

public class UnicastClient {

    private Socket socket = null;
    private PrintWriter out = null;
    private BufferedReader in = null;
    private int serverPort;//server's port number

    public UnicastClient(String serverHostname, int serverPort) {
        this.serverPort = serverPort;
        try {
            // socket = new Socket("taranis", 7);
            socket = new Socket(serverHostname, serverPort);
            System.out.println("UnicastClient:Connected to " + serverHostname + " on " + Utils.chnnl2Str(serverPort));

            out = new PrintWriter(socket.getOutputStream(), true);
            in = new BufferedReader(new InputStreamReader(
                    socket.getInputStream()));
        } catch (UnknownHostException e) {
            System.err.println("Don't know about host: " + serverHostname);

        } catch (IOException e) {
            System.err.println("Couldn't get I/O for the connection to: "
                    + serverHostname);

        }
    }

    /**
     * Send a message to the server
     * @param msg The message to send
     */
    public void sendMessage(String msg) {
        out.println(msg);
    }

    /**
     * Get a message from the server
     * @return 
     */
    public String getMessage() {
        String s = null;
        try {
            s = in.readLine();
        } catch (Exception e) {
            e.printStackTrace();
        }
        return s;
    }

    /**
     * Close connection
     */
    public void close() {
        try {
            socket.close();
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    public static void main(String[] arg) {
        System.out.print("Client");
        UnicastClient uc = new UnicastClient("127.0.0.1", Utils.UNICAST_NOTIFY_PORT);
        BufferedReader stdIn = new BufferedReader(
                new InputStreamReader(System.in));
        String userInput;

        System.out.print("input: ");
        try {
            while ((userInput = stdIn.readLine()) != null) {
                uc.sendMessage(userInput);
                System.out.println("echo: " + uc.getMessage());
                System.out.print("input: ");
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        uc.close();
    }
}
